<template>
  <BasicModal
    v-bind="$attrs"
    :destroyOnClose="true"
    :height="600"
    width="80%"
    @register="register"
    title="派单指令"
    @ok="submit"
    @cancel="cancel"
  >
    <div class="flex justify-center">
      <div class="w-[80%]">
        <DeliveryOrderHeader :data="queryParams" />
        <AreaList :data="areaList" />
        <!-- 1配送 2自提 3直发 4提送 5调拨 6退货提送 7退货自提 8快递 -->
        <!-- 配送、提送、调拨、退货提送 -->
        <Form ref="formRef" :model="queryParams" :rules="rules">
          <Distribution
            v-if="[1, 4, 5, 6].includes(queryParams.shippingType)"
            :queryParams="queryParams"
          />
          <!-- 自提 -->
          <SelfPickup v-if="[2, 7].includes(queryParams.shippingType)" :queryParams="queryParams" />
          <!-- 直发 -->
          <SendDirectly v-if="queryParams.shippingType === 3" :queryParams="queryParams" />
          <!-- 快递 -->
          <div
            v-if="queryParams.shippingType === 8"
            class="border border-solid border-black p-[20px]"
          >
            <WareHouse :queryParams="queryParams" />
          </div>
        </Form>
      </div>
    </div>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, toRaw } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { getDate } from '@/utils/time';
  import { v4 as uuidv4 } from 'uuid';
  import type { AreaDetailList, QueryDeatail } from './types/types.js';
  import { createShipping } from '@/api/deliveryOrder';

  import { Form } from 'ant-design-vue';
  import type { Rule } from 'ant-design-vue/es/form';

  import DeliveryOrderHeader from './DeliveryOrderHeader.vue';
  import AreaList from './AreaList.vue';
  import Distribution from './Distribution.vue';
  import SelfPickup from './SelfPickup.vue';
  import SendDirectly from './SendDirectly.vue';
  import WareHouse from './WareHouse.vue';

  const formRef = ref();

  const emit = defineEmits(['on-search']);

  // const props = defineProps({
  //   areaDataList: { type: Array as () => ShippingOrder[] },
  //   shippingType: { type: Number },
  // });

  // const modelRef = ref<ShippingOrder>();

  const queryParamsInit = {
    shippingType: 1,
    type: 1,
    consigneeDate: '',
    consigneeExpire: '',
    deliveryOrderIds: [],

    carrierMid: '', //承运商id
    deliveryTime: undefined, //计划送达时间
    deliveryRemark: '', //运输要求
    carrierType: '3', //运输方式
    freightTypeId: '1', //计费方式

    consigneeWarehouseId: '', // 仓库id
    warehouseRemark: '', // 出库要求
    isUrgant: 0, //是否加急
    isDelivery: 1, // 是否生成送货单
    isPrintDelivery: 1, // 是否打印送货单
    batchId: uuidv4().split('-').join(''),
    fileLabel: 'dispatch',

    shippingOrderId: 1,
    driverName: '',
    driverPhone: '',
    driverIdCard: '',
    vehicleNo: '',
    carrierName: '',
    freightType: '',
    expressNo: '',
  };

  const queryParams = ref<QueryDeatail>({
    ...queryParamsInit,
  });
  const areaList = ref<AreaDetailList>([]);

  const rules: Record<string, Rule[]> = {
    carrierMid: [{ required: true, message: '请选择承运商', trigger: 'change' }],
    deliveryTime: [{ required: true, message: '请选择计划送达时间', trigger: 'change' }],

    consigneeWarehouseId: [{ required: true, message: '请选择仓库', trigger: 'change' }],

    driverName: [{ required: true, message: '请输入司机姓名', trigger: 'blur', type: 'string' }],
    driverPhone: [{ required: true, message: '请输入联系方式', trigger: 'blur', type: 'string' }],
    vehicleNo: [{ required: true, message: '请输入车牌号', trigger: 'blur' }],
    driverIdCard: [
      { required: true, message: '请输入司机身份证', trigger: 'blur', type: 'string' },
    ],
  };

  const [register, { closeModal }] = useModalInner((data) => {
    data && onDataReceive(data);
  });

  function onDataReceive(data) {
    console.log('🚀 ~ onDataReceive ~ data:', data);
    queryParams.value.batchId = uuidv4().split('-').join('');
    queryParams.value.type = data.type;
    queryParams.value.deliveryOrderIds = data.areaDataList?.map((item) => {
      return item.id;
    });
    queryParams.value.shippingType = Number(data.shippingType);
    queryParams.value.consigneeDate = getDate.today(new Date(), 'yyyy-MM-dd');
    queryParams.value.consigneeExpire = getDate.getDateAfterDays(3, 'yyyy-MM-dd');

    if (data.shippingType === 2)
      queryParams.value.isDelivery = queryParams.value.isPrintDelivery = 0;

    console.log('🚀 ~ onDataReceive ~ queryParams.value:', queryParams.value.batchId);

    const normalize = (str) => str.replace(/市$/, '').trim();

    if (data.areaDataList && data.areaDataList.length > 0) {
      queryParams.value.consigneeWarehouse = data.areaDataList[0].consigneeWarehouse;
      if (
        normalize(data.areaDataList[0].consigneeProvince) ===
        normalize(data.areaDataList[0].receiverProvince)
      ) {
        queryParams.value.deliveryTime = getDate.getDateAfterDays(1, 'yyyy-MM-dd');
      } else {
        queryParams.value.deliveryTime = getDate.getDateAfterDays(3, 'yyyy-MM-dd');
      }
    }

    let remark = '';
    areaList.value = data.areaDataList?.map((item, index) => {
      remark = (index == 0 ? remark : remark + '\n') + item!.receiverRemark;
      return {
        consigneeProvince: item!.consigneeProvince,
        consigneeCity: item!.consigneeCity,
        consigneeArea: item!.consigneeArea,
        consigneeAddress: item!.consigneeAddress,
        consigneeAddressDisplay: item!.consigneeAddressDisplay,
        receiverProvince: item!.receiverProvince,
        receiverCity: item!.receiverCity,
        receiverArea: item!.receiverArea,
        receiverAddress: item!.receiverAddress,
        receiverAddressDisplay: item!.receiverAddressDisplay,
        distance: item!.distance,
        receiverRemark: item!.receiverRemark,
        deliveryCode: item!.deliveryCode,
      };
    });
    // 如果头部数据只有一组则运输要求和出库备注默认为receiverRemark
    if (areaList.value.length === 1) {
      queryParams.value.deliveryRemark = queryParams.value.warehouseRemark =
        areaList.value[0].receiverRemark;
    } else {
      queryParams.value.deliveryRemark = queryParams.value.warehouseRemark = remark;
    }
  }

  const cancel = async () => {
    // 清空数据
    for (let item in queryParamsInit) {
      queryParams.value[item] = queryParamsInit[item];
    }
  };

  const submit = async () => {
    console.log('values', queryParams, toRaw(queryParams));
    formRef.value
      .validate()
      .then(async () => {
        console.log('values', queryParams, toRaw(queryParams));
        await createShipping(queryParams.value);
        closeModal();
        cancel();
        emit('on-search', '');
      })
      .catch((error) => {
        console.log('error', error);
      });
  };
</script>
